const fs = require('fs').promises;

const { resolveVue } = require('./utils');

function serverPluginModuleResolve({ app, root }) {
    const moduleRE = /^\/@modules\//;

    // 编译的模块使用commonjs规范,其他文件均使用es6模块
    const vueResolved = resolveVue(root);

    app.use(async (ctx, next) => {
        // 对 /@modules 开头的路径进行映射
        if (!moduleRE.test(ctx.path)) {
            return next();
        }
        // 去掉 /@modules/路径
        const id = ctx.path.replace(moduleRE, '');
        ctx.type = 'js';
        const content = await fs.readFile(vueResolved[id], 'utf8');
        ctx.body = content
    });
}

module.exports = serverPluginModuleResolve;